package com.example.AIstudy.controller;

import com.example.AIstudy.domain.CompositionDetail;
import com.example.AIstudy.domain.CuoTiJi;
import com.example.AIstudy.domain.TranslateDetail;
import com.example.AIstudy.domain.User;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.CompositionService;
import com.example.AIstudy.service.TranslationService;
import com.example.AIstudy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.pattern.PathPattern;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.gson.Gson;

@RestController
@CrossOrigin
@RequestMapping("analyse")
@Api(tags = "分析用户答题情况API")
public class AnalyseController {
    @Autowired
    UserService userService;

    @Autowired
    CompositionService compositionService;

    @Autowired
    TranslationService translationService;
    String baseUrl;
    String []apiUrl;


    public AnalyseController() throws IOException {
        baseUrl=new File(".").getCanonicalPath()+"/features/";
        apiUrl=new String[]{baseUrl+"analysis_reading_comprehension.py",baseUrl+"evaluate_choice_question.py",
                baseUrl+"evaluate_essay.py",baseUrl+"evaluate_translation.py"};
    }

    @PostMapping("")
    @ApiOperation("分析答题情况")
    public Object analyseUserAnswer(@ApiParam("错题对象")@RequestBody CuoTiJi cuoTiJi) throws AIstudyException{
        //执行python的环境
        String anacondaUrl="python";
        //获取错题的类型
        String category=cuoTiJi.getCategory();
        //分析错题的url
        String pythonapiURL;
        //传递的参数
        String[] arg=null;
        // 根据不同的题目类型设置不同的传递参数
        if(category.equals("yuedu")){
            pythonapiURL=apiUrl[0];
            //将问题和选项封装到一个地方
            String problem=cuoTiJi.getProblem()+cuoTiJi.getChoice1()+cuoTiJi.getChoice2()+cuoTiJi.getChoice3()+cuoTiJi.getChoice4();
//            System.out.println(problem);
            //封装调用python接口的参数
            arg=new String[]{anacondaUrl, pythonapiURL, cuoTiJi.getContent() ,problem,cuoTiJi.getAnswer(),cuoTiJi.getStuAnswer()};
//            System.out.println(cuoTiJi.getAnswer());
//            System.out.println(cuoTiJi.getStuAnswer());
        }else if(category.equals("xuanze")){
            pythonapiURL=apiUrl[1];
            String problem=cuoTiJi.getProblem()+cuoTiJi.getChoice1()+cuoTiJi.getChoice2()+cuoTiJi.getChoice3()+cuoTiJi.getChoice4();
            arg=new String[]{anacondaUrl, pythonapiURL, cuoTiJi.getProblem(),cuoTiJi.getAnswer(),cuoTiJi.getStuAnswer()};
        }else if(category.equals("zuowen")){
            pythonapiURL=apiUrl[2];
            if(cuoTiJi.getScore()==0){
                cuoTiJi.setScore(25);
            }
            User user=userService.getUserByUserID(cuoTiJi.getStuID());
            arg=new String[]{anacondaUrl, pythonapiURL, cuoTiJi.getStuAnswer(),cuoTiJi.getContent(), String.valueOf(user.getOverlevel()), String.valueOf(cuoTiJi.getScore())};
        }else if(category.equals("fanyi")){
            pythonapiURL=apiUrl[3];
            if(cuoTiJi.getScore()==0){
                cuoTiJi.setScore(15);
            }
            arg=new String[]{anacondaUrl, pythonapiURL, cuoTiJi.getStuAnswer(),cuoTiJi.getContent(), String.valueOf(cuoTiJi.getScore())};
        }
        //执行python文件
        try{
            Process proc = Runtime.getRuntime().exec(arg);
            int res = proc.waitFor();
            System.out.println(res);
            if (res == 0) {
                System.out.println("成功执行");
                //成功执行 获取输出信息
                String line=null;
                BufferedReader inData = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
                StringBuilder builder=new StringBuilder();
                while ((line = inData.readLine()) != null){
                    //直接返回建议信息的字符串
                    if(category.equals("xuanze")||category.equals("yuedu")){
                        builder.append(line);
                        builder.append("\n");
                        System.out.println(line);
                    }
                    //插入数据库后再返回
                    else if(category.equals("zuowen")){
                        //如果是作文 需要将json文件转换为对象后 封装并返回
                        System.out.println(line);
                        Gson gson = new Gson();
                        CompositionDetail detail = gson.fromJson(line, CompositionDetail.class);
                        compositionService.insertCompositionDetail(detail);
                        inData.close();
                        return detail;
                    }
                    else if(category.equals("fanyi")){
                        //如果是作文 需要将json文件转换为对象后 封装并返回
                        System.out.println(line);
                        Gson gson = new Gson();
                        TranslateDetail detail = gson.fromJson(line, TranslateDetail.class);
                        translationService.insertTranslateDetail(detail);
                        inData.close();
                        return detail;
                    }
                }
                inData.close();
                return builder.toString();
            }else{
                System.out.println("执行错误");
                //未成功执行 获取错误输出信息
                String line=null;
                BufferedReader inError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "gb2312"));
                while ((line = inError.readLine()) != null) {
                    System.out.println(line);
                    throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
                }
                inError.close();
            }
            proc.waitFor();
        }catch (IOException | InterruptedException e){
            throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
        }
        return null;
    }
}
